package com.traffic.api.controller;

import com.traffic.api.entity.SmsInfo;
import com.traffic.api.service.SMSInfoService;
import com.traffic.api.sms.AlidayuSMS;
import com.traffic.api.sms.SMSUtil;
import com.traffic.api.util.BaseResponse;
import com.traffic.api.util.DateUtils;
import com.traffic.api.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.Contended;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by churcy on 2017/3/2.
 */
@Controller
public class SMSController {
    private static final Logger LOG = LoggerFactory.getLogger(SMSController.class);

    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private SMSInfoService smsInfoService;
    @Autowired
    private AlidayuSMS alidayuSMS;

    /**
     * 发送短信验证码
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sms", method = RequestMethod.POST)
    public Object sendAlidayuSMS(HttpServletRequest request) {
        String mobilePhone = request.getParameter("mobilePhone");
        Map<String, Object> obj = new HashMap<>();
        try {
            do {
                if (StringUtils.isBlank(mobilePhone)) {
                    LOG.info("param null error");
                    break;
                }
                //send
                String verificationCode = RandomUtil.createVerificationCode(4);
                Map<String, Object> response = alidayuSMS.send(mobilePhone, verificationCode);
                if (response.get("errorCode") == null || response.get("errorCode").equals("0")) {
                    obj = BaseResponse.setResponse(null, "20000", "调用成功");
                } else {
                    obj = BaseResponse.setResponse(null, "40008", "短信接口请求失败，" + response.get("subMsg"));
                }
            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("server error");
        }
        return obj;
    }

    /**
     * 发送短信验证码
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sms/abandon", method = RequestMethod.POST)
    public Object sendSMS(HttpServletRequest request) {
        String mobilePhone = request.getParameter("mobilePhone");
        Map<String, Object> obj = new HashMap<>();
        try {
            do {
                //,headers = "Accept=text/html"
                if (StringUtils.isBlank(mobilePhone)) {
                    LOG.info("param null error");
                    break;
                }
                //send
                String verificationCode = RandomUtil.createVerificationCode(4);
                String content = "【武汉电子公交卡】您正在领取电子公交卡，验证码：" + verificationCode + "。电子公交卡，无需充值，自动扣款。";

                String result = smsUtil.sendSMS(mobilePhone, content, verificationCode);
                Document document = DocumentHelper.parseText(result);
                Element root = document.getRootElement();
                Element returnstatus = root.element("returnstatus");
                String response = returnstatus.getText();
                if (response.equals("Success")) {
                    obj = BaseResponse.setResponse(null, "20000", "调用成功");
                } else {
                    obj = BaseResponse.setResponse(null, "40008", "短信接口请求失败，" + response);
                }
                LOG.info("科讯短信接口返回码为：" + response);
            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("server error");
        }
        return obj;
    }


    /**
     * 校验短信验证码
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sms/verification/code", method = RequestMethod.POST)
    public Object checkSMS(HttpServletRequest request) {
        Map<String, Object> obj = new HashMap<>();
        String mobilePhone = request.getParameter("mobilePhone");
        String verificationCode = request.getParameter("verificationCode");

        try {
            do {
                if (StringUtils.isAnyBlank(mobilePhone, verificationCode)) {
                    LOG.info("param null error");
                    obj = BaseResponse.setResponse(null, "40001", "参数错误");
                    break;
                }
                //check
                Map<String, Object> conditions = new HashMap<>();
                conditions.put("mobilePhone", mobilePhone);
                conditions.put("code", verificationCode);
                List<SmsInfo> smsInfoList = smsInfoService.findByConditions(conditions);
                if (smsInfoList == null || smsInfoList.size() == 0) {
                    obj = BaseResponse.setResponse(null, "40007", "短信验证码不存在");
                    break;
                }
                SmsInfo smsInfo = smsInfoList.get(0);
                long createTime = smsInfo.getCreateTime().getTime();
                long now = new Date().getTime();
                long exTime = createTime + 60 * 1000;

                if (exTime < now) {
                    obj = BaseResponse.setResponse(null, "40009", "短信过期");
                    break;
                }

                obj = BaseResponse.setResponse(null, "20000", "调用成功");

            } while (false);
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("server error");
        }
        return obj;
    }
}
